package com.sn.author.service.impl;
import com.alibaba.fastjson.JSON;
import com.sn.author.common.enums.*;
import com.sn.author.common.exception.BadRequestException;
import com.sn.author.dao.ImportAccountMapper;
import com.sn.author.domain.dto.AuthorDTO;
import com.sn.author.domain.entity.CollectionData;
import com.sn.author.domain.entity.ImportAccount;
import com.sn.author.domain.vo.*;
import com.sn.author.common.exception.ParamsException;
import com.sn.author.service.dao.ApiService;
import com.sn.author.service.dao.CollectionService;
import com.sn.author.service.dao.PushMessageService;
import com.sn.author.utils.AESUtil;
import com.sn.author.utils.BeanUtils;
import com.sn.author.utils.DateUtils;
import com.sn.author.utils.Utils;
import com.sn.author.redis.RedisConst;
import com.sn.author.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Slf4j
public class ApiServiceImpl implements ApiService {

    @Resource
    private ImportAccountMapper importAccountMapper;

    @Autowired
    private PushMessageService pushMessageService;

    @Autowired
    private CollectionService collectionService;

    public AuthorDTO authorCode(String key) throws Exception {
        if(key == null || "".equals(key)){
            throw new ParamsException();
        }
        String time = RedisUtil._REDIS_MODULE.hmget(RedisConst._KEY_MAP,key);
        if(time == null){
            return new AuthorDTO(false,System.currentTimeMillis());
        }
        String sing = buildSing();
        //缓存
        RedisUtil._REDIS_MODULE.set(sing,1);
        return new AuthorDTO(true,sing,System.currentTimeMillis());
    }

    private String buildSing() throws Exception {
        return AESUtil.encrypt(Utils.getGuid());
    }

    public boolean heart(HeartVo heartVo) {
        return RedisUtil._REDIS_MODULE.get(heartVo.getSing()) != null;
    }

    @Override
    public Boolean callback(CallbackVo callbackVo) {

        Optional<CallbackEnum> opt = CallbackEnum.match(callbackVo.getType());
        if(!opt.isPresent()){
            throw new BadRequestException("异常的类型 :" + callbackVo.getType());
        }

        if(callbackVo.getMessage() == null){
            throw new BadRequestException("注册回调的消息为空");
        }

        switch (opt.get()){
            case LOGIN_TYPE:
            case REGISTER_TYPE:
                doParserRegisterMessage(callbackVo.getMessage());
                break;
            case COLLECTION:
                doParserCollectionMessage(callbackVo.getMessage());
                break;
            default:
                throw new BadRequestException("不存在的回调消息类型 type:" + callbackVo.getType());
        }
        return true;
    }

    private void doParserCollectionMessage(String message) {
        CollectionCommitVo commitData = JSON.parseObject(message,CollectionCommitVo.class);
        if(commitData == null || commitData.getRows() == null || commitData.getRows().isEmpty()){
            log.warn("未采集到任何数据");
            return;
        }
        List<CollectionVo> list = commitData.getRows();
        log.info("收到采集信息回调请求 taskId:{} 数量:{}",commitData.getTaskId(),list.size());

        List<CollectionData> insertData = BeanUtils.coventObject(list, CollectionData.class);
        insertData.forEach(item -> item.setTaskId(commitData.getTaskId()));
        collectionService.saveCommitData(insertData);

        //更新任务状态
        collectionService.updateTaskStatus(commitData.getTaskId() + "", CollectionStatusEnum.FINISH);
    }

    private void doParserRegisterMessage(String message) {
        RegisterVo registerVo = JSON.parseObject(message, RegisterVo.class);
        if(registerVo == null){
            throw new BadRequestException("转换注册回调消息模型失败 callback message:" + message);
        }
        //数据校验
        validRegisterModel(registerVo);
        //保存到数据库
        ImportAccount importAccount = importAccountMapper.selectByPhone(registerVo.getPhone());
        if(importAccount != null){
            importAccount.setPassword(registerVo.getPassword());
            importAccount.setUrlParam(registerVo.getUrlParam());
            importAccount.setHeader(registerVo.getHeader());
        }else{
            importAccount = new ImportAccount();
            importAccount.setPassword(registerVo.getPassword());
            importAccount.setStatus(StatusEnum.NORMAL.getStatus());
            importAccount.setImportTime(DateUtils.formatYMDHMS(new Date()));
            importAccount.setLastLoginTime(DateUtils.formatYMDHMS(new Date()));
            importAccount.setImportUser("");
            importAccount.setImportUserId(-1L);
            importAccount.setLoginStatus(LoginStatusEnum.LOGIN.getStatus());
            importAccount.setUrlParam(registerVo.getUrlParam());
            importAccount.setHeader(registerVo.getHeader());
            importAccount.setPhone(registerVo.getPhone());
            importAccountMapper.insert(importAccount);
        }
        String pushMsg = "注册成功 账号:[" + registerVo.getPhone() + "] 密码:[" + registerVo.getPassword() + "]";
        log.info(pushMsg);
        pushMessageService.pushMessage(PushMessageService.buildTaskPushMessage(pushMsg,"-1", TaskTypeEnum.LOGIN.getType()));
    }

    private void validRegisterModel(RegisterVo registerVo) {
        if(registerVo.getPhone() == null){
            throw new BadRequestException("手机号码为空");
        }
        if(registerVo.getUrlParam() == null){
            throw new BadRequestException("urlParam为空");
        }
        if(registerVo.getHeader() == null){
            throw new BadRequestException("header为空");
        }
        if(registerVo.getPassword() == null){
            throw new BadRequestException("密码为空");
        }
    }
}
